package org.budo.netty.servlet.util;

import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @author limingwei
 */
public class StreamUtil {
    public static void write(InputStream inputStream, OutputStream outputStream) {
        try {
            byte[] buf = new byte[1024];
            int flag = 0;
            while ((flag = inputStream.read(buf)) != -1) {
                outputStream.write(buf, 0, flag);
            }
        } catch (Throwable e) {
            throw new RuntimeException(e);
        } finally {
            close(outputStream);
            close(inputStream);
        }
    }

    private static void close(Closeable closeable) {
        try {
            closeable.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static String toString(InputStream inputStream) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        write(inputStream, byteArrayOutputStream);
        return new String(byteArrayOutputStream.toByteArray());
    }

    public static byte[] charsToBytes(char[] buf) {
        byte[] bytes = new byte[buf.length];
        for (int i = 0; i < buf.length; i++) {
            bytes[i] = (byte) buf[i];
        }
        return bytes;
    }
}